package com.wuzf.navigation_test.ui;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import androidx.paging.PagedList;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wuzf.navigation_test.R;
import com.wuzf.navigation_test.databinding.LayoutPageListBinding;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


public abstract class AbsListFragment<T, M extends AbsViewModel<T>> extends Fragment implements OnRefreshListener, OnLoadMoreListener {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private PagedListAdapter adapter;
    private View emptyView;
    private M mViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LayoutPageListBinding inflate = LayoutPageListBinding.inflate(inflater, container, false);
        View root = inflate.getRoot();
        refreshLayout = root.findViewById(R.id.refresh_layout);
        recyclerView = root.findViewById(R.id.recycler_view);
        emptyView = root.findViewById(R.id.empty_view);

        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 取消列表动画
        recyclerView.setItemAnimator(null);
        adapter = getAdapter();
        recyclerView.setAdapter(adapter);
        // 设置中间的横线
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
        decoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.list_divider));
        recyclerView.addItemDecoration(decoration);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Type type = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type[] arguments = parameterizedType.getActualTypeArguments();
        if (arguments.length > 1) {
            Type argument = arguments[1];
            Class subclass = ((Class) argument).asSubclass(ViewModel.class);
            mViewModel = (M) ViewModelProviders.of(this).get(subclass);
            mViewModel.getLiveData().observe(getViewLifecycleOwner(), new Observer<PagedList<T>>() {
                @Override
                public void onChanged(PagedList<T> ts) {
                    adapter.submitList(ts);
                }
            });
            mViewModel.getBoundaryLiveData().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
                @Override
                public void onChanged(Boolean aBoolean) {
                    finishRefresh(aBoolean);
                }
            });
        }

        // 实现该方法实现在onViewCreated中操作数据
        afterViewCreated();
    }

    protected abstract PagedListAdapter getAdapter();

    protected abstract void afterViewCreated();

    // 生成的数据，保存到recyclerView中
    private void submitList(PagedList<T> list) {
        if (list.size() > 0) {
            adapter.submitList(list);
        }
        finishRefresh(list.size() > 0);
    }

    private void finishRefresh(boolean hasData) {
        PagedList currentList = adapter.getCurrentList();
        // 当列表中存在数据的时候，才能够刷新
        boolean isRefresh = hasData || (currentList != null && currentList.size() > 0);
        RefreshState state = refreshLayout.getState();
        if (state.isOpening && state.isFooter) {
            refreshLayout.finishLoadMore();
        } else if (state.isOpening && state.isHeader) {
            refreshLayout.finishRefresh();
        }
        if (isRefresh) {
            emptyView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.VISIBLE);
        }
    }
}
